package com.itheima.service.imp;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.aliyun.properties.JwtProperties;
import com.aliyun.utils.JwtUtils;
import com.itheima.dto.ChangeUserDto;
import com.itheima.dto.EmpDto;
import com.itheima.dto.EmpLoginDto;
import com.itheima.dto.SaveEmpDto;
import com.itheima.mapper.EmpExpMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.EmpExpr;

import com.itheima.service.EmpService;
import com.itheima.utils.CopyUtil;

import com.itheima.vo.EmpVo;
import com.itheima.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    EmpMapper empMapper;


    @Override
    public EmpVo queryPage(EmpDto empDto) {
        if(empDto.getBegin().length()==0){
            empDto.setBegin(null);
        }
        if(empDto.getEnd().length()==0){
            empDto.setEnd(null);
        }
        EmpVo empVo = new EmpVo();
        Integer page=(empDto.getPage()-1)*empDto.getPageSize();
        empDto.setPage(page);
        empVo.setRows(empMapper.querylist(empDto));
        empVo.setTotal(empMapper.queryCount());
        return empVo;
    }

    @Autowired
    EmpExpMapper empExpMapper;
    @Override
    public void save(SaveEmpDto empDto) {
       int has= empMapper.getByName(empDto.getName());
       if(has>0){
           empMapper.updateByname(empDto);

       }
       else{
           Emp emp = new Emp();
           BeanUtils.copyProperties(empDto,emp);
           System.out.println("新增员工"+emp);
           empMapper.save(emp);
           for(EmpExpr expr:empDto.getExprList()){
               expr.setEmpId(emp.getId());
               empExpMapper.save(expr);
       }

        }

    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        for(Integer id:ids){
            empMapper.deleteById(id);
        }
    }

    @Override
    public SaveEmpDto queryById(Integer id) {
        SaveEmpDto empDto = new SaveEmpDto();
       Emp emp =  empMapper.queryById(id);
        List<EmpExpr>empExprList = empExpMapper.queryByEmpId(id);
       BeanUtils.copyProperties(emp,empDto);
        empDto.setExprList(empExprList);
        return empDto;
    }

    @Override
    public List<Emp> list() {
        return empMapper.queryAll();
    }


    @Autowired
    JwtProperties jwtProperties;
    @Override
    public LoginVo login(EmpLoginDto empLoginDto) {
        LoginVo loginVo = new LoginVo();

        Emp emp=empMapper.check(empLoginDto.getUsername());
        if(emp==null){
            log.info("emp:"+emp);
            log.info("LoginDto"+empLoginDto);
            throw new RuntimeException("用户名不存在");

        }else if(!SecureUtil.md5(empLoginDto.getPassword()).equals(emp.getPassword())){
            log.info("密文"+SecureUtil.md5(empLoginDto.getPassword()));
         throw new RuntimeException("密码错误");
        }
        else{
            loginVo.setUsername(emp.getName());
            loginVo.setPassword(emp.getPassword());
            loginVo.setId(emp.getId());
            Map map=new HashMap();
            map.put("id",emp.getId());
            map.put("name",emp.getName());


            loginVo.setToken(JwtUtils.getJwt(map,jwtProperties.getSecretKey(), jwtProperties.getTtl()));

        }
        return loginVo;
        }

    @Override
    public void changePassword(ChangeUserDto changeUserDto) {
        log.info("ChangeUserDto"+changeUserDto.getPassword());
        HttpServletRequest servletRequest=  ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String jwt=servletRequest.getHeader("Token");
        Map<String,Object> map=  Jwts.parser()
                .setSigningKey(jwtProperties.getSecretKey())
                .parseClaimsJws(jwt).getBody();
        String userId=map.get("id").toString();
        Emp emp=empMapper.queryById(Integer.parseInt(userId));
        if(!SecureUtil.md5(changeUserDto.getPassword()).equals(emp.getPassword())){
            log.info("原始密文"+SecureUtil.md5(changeUserDto.getPassword()));
            throw new RuntimeException("原始密码错误");
        }else{
            emp.setPassword(SecureUtil.md5(changeUserDto.getNewpassword()));
            empMapper.changePassword(emp);
        }
    }


}
